#! /usr/bin/env python
#coding=utf-8
import smtplib
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

import os

class mail(object):
    def __init__(self,serv,account,password):
        self.serv = serv
        self.account = account
        self.password = password

    def send(self,to,title,content,file_name):
        server = smtplib.SMTP(self.serv)
        server.docmd("EHLO server")
        server.starttls()
        server.login(self.account,self.password) #仅smtp服务器需要验证时

        # 构造MIMEMultipart对象做为根容器
        main_msg = MIMEMultipart()
 
        # 构造MIMEText对象做为邮件显示内容并附加到根容器
        text_msg = MIMEText(content)
        main_msg.attach(text_msg)
 
        # 构造MIMEBase对象做为文件附件内容并附加到根容器
        contype = 'application/octet-stream'
        maintype, subtype = contype.split('/', 1)
 
        ## 读入文件内容并格式化
        f = open(file_name, 'rb')
        file_msg = MIMEBase(maintype, subtype)
        file_msg.set_payload(f.read())
        f.close()
        encoders.encode_base64(file_msg) 
        
        ## 设置附件头
        basename = os.path.basename(file_name)
        file_msg.add_header('Content-Disposition','attachment', filename = basename)
        main_msg.attach(file_msg)
 
        # 设置根容器属性
        main_msg['From'] = self.account
        main_msg['To'] = to
        main_msg['Subject'] = title
        
        # 得到格式化后的完整文本
        fullText = main_msg.as_string()
 
        # 用smtp发送邮件
        try:
            server.sendmail(self.account, to, fullText)
        finally:
            server.quit()
            print 'send success'
            
if __name__=='__main__':
    gmail = mail('smtp.gmail.com','alawn84@gmail.com','key332527')
    gmail.send('falling84@gmail.com','my test','have test.py','test.py')